package com.chinda.common.security;

import com.chinda.common.enums.MessageEnum;
import com.chinda.common.enums.UserStatusEnum;
import com.chinda.modules.sys.entity.SysRoleEntity;
import com.chinda.modules.sys.service.SysRoleService;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 自定义登录验证
 *
 * @author Wang Chinda
 * @date 2020/7/11
 * @see
 * @since 1.0
 */
@Component
@AllArgsConstructor
public class UserAuthenticationProvider implements AuthenticationProvider {


    private final SysUserDetailsService sysUserDetailsService;
    private final SysRoleService sysRoleService;


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 获取表单中输入的用户名
        String username = (String) authentication.getPrincipal();
        // 获取表单中输入的密码
        String password = (String) authentication.getCredentials();
        // 查询用户名是否存在
        SysUserDetails userDetails = sysUserDetailsService.loadUserByUsername(username);
        if (null == userDetails) {
            throw new UsernameNotFoundException(MessageEnum.SYS_SECURITY_0011.getMsg());
        }
        // 判断密码是否正确, 密码使用BCryptPasswordEncoder进行加密
        if (!new BCryptPasswordEncoder().matches(password, userDetails.getPassword())) {
            throw new BadCredentialsException(MessageEnum.SYS_SECURITY_0010.getMsg());
        }
        // 判断账户是否停用
        if (!UserStatusEnum.NORMAL.equals(userDetails.getStatus())) {
            throw new LockedException(MessageEnum.SYS_SECURITY_0012.getMsg());
        }
        // 判断账户是否过期
        if (userDetails.isAccountNonExpired()) {
            throw new AccountExpiredException(MessageEnum.SYS_SECURITY_0013.getMsg());
        }
        // 判断账户是否锁定
        if(userDetails.isAccountNonLocked()) {
            throw new LockedException(MessageEnum.SYS_SECURITY_0009.getMsg());
        }
        // 判断账户失效
        if (!userDetails.isEnabled()) {
            throw new DisabledException(MessageEnum.SYS_SECURITY_0014.getMsg());
        }
        // 判断证书是否过期
        if (userDetails.isCredentialsNonExpired()) {
            throw new CredentialsExpiredException(MessageEnum.SYS_SECURITY_0015.getMsg());
        }
        // 查询用户角色
        List<SysRoleEntity> sysRoleEntityList = sysRoleService.selectSysRoleByUserId(userDetails.getUserId());
        // 角色集合
        Set<GrantedAuthority> authorities = sysRoleEntityList.stream().map(sysRoleEntity ->
                new SimpleGrantedAuthority("ROLE_" + sysRoleEntity.getRoleName())).collect(Collectors.toSet());
        userDetails.setAuthorities(authorities);
        // 登录
        return new UsernamePasswordAuthenticationToken(userDetails, password, authorities);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }
}
